package com.klm.netty.codec;

import com.google.protobuf.MessageLite;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ProtobufEncoder extends MessageToByteEncoder<MessageLite> {
    @Override
    protected void encode(ChannelHandlerContext ctx, MessageLite msg, ByteBuf out) throws Exception {
        try {
            byte[] body = msg.toByteArray();
            int length = body.length;
            
            // 写入消息长度
            out.writeInt(length);
            // 写入消息体
            out.writeBytes(body);
            
            log.debug("Encoded message: {}, length: {}", msg.getClass().getSimpleName(), length);
        } catch (Exception e) {
            log.error("Failed to encode message", e);
            throw e;
        }
    }
} 